﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.Runtime.InteropServices;
using System.IO;
using System.IO.Compression;
using System.Xml;
using Newtonsoft.Json;
using System.Configuration;
using Ionic.Zip;

namespace MechanicsLab
{
    public class FenYiPress
    {
        string connStr = "";

        public FenYiPress(string path)
        {
            //connStr = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Persist Security Info=False;";
            connStr = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Jet OLEDB:Database Password=123;";
        }

        /// <summary>
        /// 解压ZIP文件
        /// </summary>
        /// <param name="strZipPath">待解压的ZIP文件</param>
        /// <param name="strUnZipPath">解压的目录</param>
        /// <param name="overWrite">是否覆盖</param>
        /// <returns>成功：true/失败：false</returns>
        public static bool Decompression(string strZipPath, string strUnZipPath, bool overWrite)
        {
            try
            {
                ReadOptions options = new ReadOptions();
                options.Encoding = Encoding.Default;//设置编码，解决解压文件时中文乱码
                using (ZipFile zip = ZipFile.Read(strZipPath, options))
                {
                    foreach (ZipEntry entry in zip)
                    {
                        if (string.IsNullOrEmpty(strUnZipPath))
                        {
                            strUnZipPath = strZipPath.Split('.')[0];
                        }
                        if (overWrite)
                        {
                            entry.Extract(strUnZipPath, ExtractExistingFileAction.OverwriteSilently);//解压文件，如果已存在就覆盖
                        }
                        else
                        {
                            entry.Extract(strUnZipPath, ExtractExistingFileAction.DoNotOverwrite);//解压文件，如果已存在不覆盖
                        }
                    }
                    return true;
                }
            }
            catch (Exception)
            {
                return false;
            }
        }

        public void GetCur(byte[] buffer, string precativeNum,string path,string path1)
        {
            FileStream fsq = new FileStream(path, FileMode.Create);
            //开始写入
            fsq.Write(buffer, 0, buffer.Length);
            //清空缓冲区、关闭流
            fsq.Flush();
            fsq.Close();
            Decompression(path, path1, true);  
        }

        /// <summary>
        /// 万能机上传数据
        /// </summary>
        /// <param name="precativeNum"></param>
        /// <param name="name"></param>
        /// <param name="remark_1"></param>
        /// <returns></returns>
        public string PostData(string precativeNum, string name, string remark_1)
        {
            string path = System.Windows.Forms.Application.StartupPath + "\\Data\\" + precativeNum + ".zip";
            string path1 = System.Windows.Forms.Application.StartupPath + "\\Data\\" + precativeNum;
            List<PostDataPress> postdata = new List<PostDataPress>(); 
            DataTable dt = SelPostData(precativeNum);
            if (dt != null)
            {
                if (dt.Rows.Count > 0)
                {
                    byte[] buffer = dt.Rows[0]["Datas"] as byte[];
                    GetCur(buffer, precativeNum, path, path1);

                    XmlTextReader reader = new XmlTextReader(path1 + "\\Result.xml");
                    while (reader.Read())
                    {
                        if (reader.Name == "z:row")
                        {
                            PostDataPress chp = new PostDataPress();
                            chp.trialName = name;
                            chp.equNum = ConfigurationManager.AppSettings["Number"];
                            //一组数据ID
                            chp.ID = remark_1;
                            //试验单号 
                            chp.Number = precativeNum;
                            //力值
                            chp.Force1 = reader.GetAttribute("Fm");
                            chp.Force2 = reader.GetAttribute("FeH");
                            //强度
                            chp.Compress1 = reader.GetAttribute("Rm");
                            chp.Compress2 = reader.GetAttribute("ReH");

                            if (File.Exists(path1 + "\\Data.xml"))
                            {
                                XmlTextReader reader1 = new XmlTextReader(path1 + "\\Data.xml");
                                while (reader1.Read())
                                {
                                    if (reader1.Name == "z:row")
                                    {
                                        if (reader.GetAttribute("ID").Equals(reader1.GetAttribute("ID")))
                                        {
                                            chp.Curve1.Add(reader1.GetAttribute("Second") + "," + reader1.GetAttribute("Force"));
                                        }
                                    }
                                }
                            }
                            postdata.Add(chp);
                        }    
                    }
                }
            }
            string jsonstr = JsonConvert.SerializeObject(postdata);
            string str = Pub.HttpPost(ConfigurationManager.AppSettings["PostDataUrl"], jsonstr);
            return str;
        }

        /// <summary>
        /// 压力机上传数据
        /// </summary>
        /// <param name="precativeNum"></param>
        /// <param name="name"></param>
        /// <param name="remark_1"></param>
        /// <returns></returns>
        public string PostData1(string precativeNum, string name, string remark_1)
        {
            string path = System.Windows.Forms.Application.StartupPath + "\\Data\\" + precativeNum + ".zip";
            string path1 = System.Windows.Forms.Application.StartupPath + "\\Data\\" + precativeNum;
            List<PostDataPress> postdata = new List<PostDataPress>();
            DataTable dt = SelPostData(precativeNum);
            if (dt != null)
            {
                if (dt.Rows.Count > 0)
                {
                    byte[] buffer = dt.Rows[0]["Datas"] as byte[];
                    GetCur(buffer, precativeNum, path, path1);

                    XmlTextReader reader = new XmlTextReader(path1 + "\\Result.xml");
                    while (reader.Read())
                    {
                        if (reader.Name == "z:row")
                        {
                            if (reader.GetAttribute("ID").Equals("1") || reader.GetAttribute("ID").Equals("4") || reader.GetAttribute("ID").Equals("6"))
                            {

                                PostDataPress chp = new PostDataPress();
                                chp.trialName = name;
                                chp.equNum = ConfigurationManager.AppSettings["Number"];
                                //一组数据ID
                                chp.ID = remark_1;
                                //试验单号 
                                chp.Number = precativeNum;
                                //力值及强度值
                                chp.Force1 = reader.GetAttribute("Fm");
                                chp.Compress1 = reader.GetAttribute("Rm");
                                //曲线
                                XmlTextReader reader1 = new XmlTextReader(path1 + "\\Data.xml");
                                while (reader1.Read())
                                {
                                    if (reader1.Name == "z:row")
                                    {
                                        if (reader.GetAttribute("ID").Equals(reader1.GetAttribute("ID")))
                                        {
                                            chp.Curve1.Add(reader1.GetAttribute("Second") + "," + reader1.GetAttribute("Force"));
                                        }
                                    }
                                }
                                postdata.Add(chp);
                            }
                            else if (reader.GetAttribute("ID").Equals("2") || reader.GetAttribute("ID").Equals("5") || reader.GetAttribute("ID").Equals("7"))
                            {
                                postdata[postdata.Count - 1].Force2 = reader.GetAttribute("Fm");
                                postdata[postdata.Count - 1].Compress2 = reader.GetAttribute("Rm");

                                XmlTextReader reader1 = new XmlTextReader(path1 + "\\Data.xml");
                                while (reader1.Read())
                                {
                                    if (reader1.Name == "z:row")
                                    {
                                        if (reader.GetAttribute("ID").Equals(reader1.GetAttribute("ID")))
                                        {
                                            postdata[postdata.Count - 1].Curve2.Add(reader1.GetAttribute("Second") + "," + reader1.GetAttribute("Force"));
                                        }
                                    }
                                }
                            }
                            else if (reader.GetAttribute("ID").Equals("3") || reader.GetAttribute("ID").Equals("6") || reader.GetAttribute("ID").Equals("9"))
                            {
                                postdata[postdata.Count - 1].Force3 = reader.GetAttribute("Fm");
                                postdata[postdata.Count - 1].Compress3 = reader.GetAttribute("Rm");

                                XmlTextReader reader1 = new XmlTextReader(path1 + "\\Data.xml");
                                while (reader1.Read())
                                {
                                    if (reader1.Name == "z:row")
                                    {
                                        if (reader.GetAttribute("ID").Equals(reader1.GetAttribute("ID")))
                                        {
                                            postdata[postdata.Count - 1].Curve3.Add(reader1.GetAttribute("Second") + "," + reader1.GetAttribute("Force"));
                                        }  
                                    }
                                }
                            }
                        }
                    }
                }
            }
            string jsonstr = JsonConvert.SerializeObject(postdata);
            string str = Pub.HttpPost(ConfigurationManager.AppSettings["PostDataUrl"], jsonstr);
            return str;
        }

        /// <summary>
        /// 获取上传数据
        /// </summary>
        /// <param name="precativeNum"></param>
        /// <returns></returns>
        public DataTable SelPostData(string precativeNum)
        {
            DataTable dt = null;
            try
            {
                string sql = "select Datas from TestData where SampleNo='" + precativeNum + "'";
                dt = Query(sql);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return dt;
        }

        public DataTable Query(string sql)
        {
            OleDbConnection conn = null;
            try
            {
                DataTable table = new DataTable();
                conn = new OleDbConnection(connStr);
                conn.Open();
                using (OleDbDataAdapter da = new OleDbDataAdapter(sql, conn))
                {
                    da.Fill(table);
                }
                return table;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                conn.Close();
            }
        }
    }
}
